package org.ahuanlien.crm.web.controller;

import org.ahuanlien.crm.domain.Employee;
import org.ahuanlien.crm.query.EmployeeQueryObject;
import org.ahuanlien.crm.service.IEmployeeService;
import org.ahuanlien.crm.util.JSONResult;
import org.ahuanlien.crm.util.PageResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("employee")
public class EmployeeController {

	@Autowired
	private IEmployeeService employeeService;


	//打开页面和数据获取分开
	@RequestMapping("view")
	@RequiresPermissions(value = {"employee:view", "员工视图"}, logical = Logical.OR)
	public String view() {
		return "employee/view";
	}

	@RequestMapping("query")
	@ResponseBody
	@RequiresPermissions(value = {"employee:query", "员工列表"}, logical = Logical.OR)
	public PageResult query(EmployeeQueryObject qo) {
		PageResult result = employeeService.query(qo);
		return result;
	}

	@RequestMapping("validateUsername")
	@ResponseBody
	public Boolean validateUsername(String username, Long id) {
		Employee employee = employeeService.getByUsername(username);
		return employee == null || employee.getId() == id;
	}


	@RequestMapping("saveOrUpdate")
	@ResponseBody
	@RequiresPermissions(value = {"employee:saveOrUpdate", "员工保存/编辑"}, logical = Logical.OR)
	public JSONResult saveOrUpdate(Employee employee) {
		try {
			employeeService.saveOrUpdate(employee);
		} catch (Exception e) {
			e.printStackTrace();
			return JSONResult.mark("操作失败");
		}
		return JSONResult.success("操作成功");
	}

	@RequestMapping("changeState")
	@ResponseBody
	@RequiresPermissions(value = {"employee:changeState", "员工状态设置"}, logical = Logical.OR)
	public JSONResult changeState(Long id) {
		try {
			employeeService.changeState(id);
		} catch (Exception e) {
			e.printStackTrace();
			return JSONResult.mark("操作失败");
		}
		return JSONResult.success("操作成功");
	}

	@RequestMapping("initPassword")
	@ResponseBody
	@RequiresPermissions(value = {"employee:initPassword", "员工密码重置"}, logical = Logical.OR)
	public JSONResult initPassword(Long id) {
		try {
			employeeService.initPassword(id);
		} catch (Exception e) {
			e.printStackTrace();
			return JSONResult.mark("操作失败");
		}
		return JSONResult.success("操作成功");
	}

	@RequestMapping("selectAll")
	@ResponseBody
	public List<Employee> selectAll(){
		return employeeService.selectAll();

	}
}
